/*
 * 地址选择
 */
'use strict';
import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    TouchableOpacity,
    Image,
    PixelRatio,
    Platform,
    AsyncStorage,
    TextInput,
} from 'react-native';

import Picker from 'react-native-picker';

import Toast from 'antd-mobile/lib/toast';
import List from 'antd-mobile/lib/list';
import InputItem from 'antd-mobile/lib/input-item';
import ActivityIndicator from 'antd-mobile/lib/activity-indicator';

import NavTitle from '../component/NavTitle';

const Item = List.Item;
import { createForm } from 'rc-form';

var ImagePicker = require('react-native-image-picker');

import XFetch from '../XFetch';

let _selectId;

class EditPerson extends Component {
    constructor(props) {
        super(props)

        this.state = {
            pickerValue: [],
            citys: [],
            provices:[],
            countrys:[],
            streets:[],
            animating:false,
            last:false,
            resultAddr:[],
            logoImage:{}
        }
    }

    componentDidMount(){
        this._changeAddress(0,'provices');
        this.geUserinfo();
    }

    geUserinfo(){
        XFetch(`http://www.weiweigo.com/app/member.aspx?method=detail`,{
            method:'post'
        }).then(data=>{
            if(data.imgUrl) {
                this.props.form.setFieldsValue({
                    name:data.name
                });
                _selectId = data.addressId;
                this.setState({
                    logoImage: {uri:`http://www.weiweigo.com${data.imgUrl}`},
                    resultAddr:data.addressName.split(' ')
                })
            }
        });
    }

    _uploadImg(img,obj) {
        let myHeaders = new Headers();
        myHeaders.append('Content-Type', 'multipart/form-data');

        let formData = new FormData();

        formData.append('imgFile', {uri: img.uri, name: img.fileName, type: 'image/jpeg'});
        formData.append('c', 4);

        fetch(`http://www.weiweigo.com/app/member.aspx?method=upImg`,{
            method: 'POST',
            headers:myHeaders,
            body: formData,
        })
            .then(res => {
                res.json().then(data=>{
                    if(data.success){
                        obj.imgUrl=data.val;
                    }else{
                        this.setState({
                            animating:false
                        });
                        clearInterval(this._timer);
                    }
                });
            })
    }

    _matchHttpImgs(url){
        return /^(http)/g.test(url);
    }

    _register(){
        if(!_selectId){
            Toast.fail('地址未选择',2);
            return;
        }
        this.props.form.validateFields((error, value) => {
            if(!error){
                this.setState({
                    animating:true
                });
                let imgUrl = {};

                if(this._matchHttpImgs(this.state.logoImage.uri)){
                    imgUrl.imgUrl = this.state.logoImage.uri.replace('http://www.weiweigo.com','');
                }else {
                    this._uploadImg(this.state.logoImage, imgUrl);
                }

                this._timer = setInterval(function(){
                     if(imgUrl.imgUrl) {
                         let formData = new FormData();

                         formData.append('name', value.name);
                         formData.append('addressID', _selectId);
                         formData.append('imgUrl', imgUrl.imgUrl);

                         fetch(`http://www.weiweigo.com/app/member.aspx?method=editInfo`, {
                             method: 'POST',
                             headers: {
                                 "Content-Type": "application/x-www-form-urlencoded"
                             },
                             body: formData
                         }).then(data=> {
                             data.json().then(data=> {
                                 clearInterval(this._timer);
                                 Toast.info(data.msg);
                                 AsyncStorage.setItem('username', value.name, ()=> {
                                     this.setState({
                                         username: value.name
                                     })
                                 });
                                 this.props.navigator.popToTop();
                             })
                         });
                     }
                }.bind(this),100);
            }
        })
    }


    _changeAddress(ID=0){
        this.setState({
            animating:true,
        })
        XFetch(`http://www.weiweigo.com/app/address.aspx?method=show&pid=${ID}`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                provices:data.map(ele=>{
                    return {
                        label:ele.NAME,
                        value:ele.ID
                    }
                }),
                animating:false,
            })
        });
    }

    _changeAddress2(ID){
        this.setState({
            animating:true,
        })
        XFetch(`http://www.weiweigo.com/app/address.aspx?method=show&pid=${ID}`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                citys:data.map(ele=>{
                    return {
                        label:ele.NAME,
                        value:ele.ID
                    }
                }),
                animating:false,
            })
        });
    }

    _changeAddress3(ID){
        this.setState({
            animating:true,
        })
        XFetch(`http://www.weiweigo.com/app/address.aspx?method=show&pid=${ID}`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                countrys:data.map(ele=>{
                    return {
                        label:ele.NAME,
                        value:ele.ID
                    }
                }),
                animating:false,
            })
        });
    }

    _changeAddress4(ID){
        this.setState({
            animating:true,
        })
        XFetch(`http://www.weiweigo.com/app/address.aspx?method=show&pid=${ID}`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                streets:data.map(ele=>{
                    return {
                        label:ele.NAME,
                        value:ele.ID
                    }
                }),
                animating:false,
            })
        });
    }

    _selectProvice(){
        let data = [];
        this.state.provices.map(ele=>{
            data.push(ele.label);
        })
        Picker.init({
            pickerData: data,
            pickerConfirmBtnText:'确定',
            pickerCancelBtnText:'取消',
            pickerTitleText:'地址选择',
            onPickerConfirm: data => {
                if(!this.state.resultAddr.some((ele)=>{return ele == data})){
                    this.setState({
                        resultAddr:[data],
                        citys:[],
                        countrys:[],
                        streets:[]
                    },()=>{
                        this.state.provices.map(ele=>{
                            if(ele.label == data){
                                _selectId = null;
                                this._changeAddress2(ele.value);
                            }
                        })
                    })
                }
            },
        });
        Picker.show();
    }

    _selectCity(){
        if(this.state.citys.length == 0){
            Toast.info('请先选择上级',2);
            return;
        }
        let data = [];
        this.state.citys.map(ele=>{
            data.push(ele.label);
        })
        Picker.init({
            pickerData: data,
            pickerConfirmBtnText:'确定',
            pickerCancelBtnText:'取消',
            pickerTitleText:'地址选择',
            onPickerConfirm: data => {
                if(!this.state.resultAddr.some((ele)=>{return ele == data})) {
                    this.setState({
                        resultAddr: [this.state.resultAddr[0], data],
                        countrys:[],
                        streets:[]
                    }, ()=> {
                        this.state.citys.map(ele=> {
                            if (ele.label == data) {
                                _selectId = null;
                                this._changeAddress3(ele.value);
                            }
                        })
                    })
                }
            },
        });
        Picker.show();
    }

    _selectCounty(){
        if(this.state.countrys.length == 0){
            Toast.info('请先选择上级',2);
            return;
        }
        let data = [];
        this.state.countrys.map(ele=>{
            data.push(ele.label);
        })
        Picker.init({
            pickerData: data,
            pickerConfirmBtnText:'确定',
            pickerCancelBtnText:'取消',
            pickerTitleText:'地址选择',
            onPickerConfirm: data => {
                if(!this.state.resultAddr.some((ele)=>{return ele == data})) {
                    this.setState({
                        resultAddr: [this.state.resultAddr[0],this.state.resultAddr[1], data],
                        streets:[]
                    }, ()=> {
                        this.state.countrys.map(ele=> {
                            if (ele.label == data) {
                                _selectId = null;
                                this._changeAddress4(ele.value);
                            }
                        })
                    })
                }
            },
        });
        Picker.show();
    }

    _selectStreet(){
        if(this.state.streets.length == 0){
            Toast.info('请先选择上级',2);
            return;
        }
        let data = [];
        this.state.streets.map(ele=>{
            data.push(ele.label);
        })
        Picker.init({
            pickerData: data,
            pickerConfirmBtnText:'确定',
            pickerCancelBtnText:'取消',
            pickerTitleText:'地址选择',
            onPickerConfirm: data => {
                if(!this.state.resultAddr.some((ele)=>{return ele == data})) {
                    this.state.countrys.map(ele=> {
                        if (ele.label == data) {
                            _selectId = ele.value;
                        }
                    });
                    this.setState({
                        resultAddr: [...this.state.resultAddr, data]
                    });
                }
            },
        });
        Picker.show();
    }

    _selectLogo(){
        let options = {
            title: '',
            cancelButtonTitle:'取消',
            takePhotoButtonTitle:'拍照',
            chooseFromLibraryButtonTitle:'相册选择',
            mediaType:'photo',
            quality: 0.5
        };
        ImagePicker.showImagePicker(options, (response) => {
            let source = null;

            if(response.didCancel){
                return;
            }

            if(Platform.OS === 'ios') {
                // uri (on iOS)
                source = {uri: response.uri.replace('file://', ''), isStatic: true,fileName:response.fileName};
            } else {
                // uri (on android)
                source = {uri: response.uri, isStatic: true, fileName:response.fileName};
            }

            this.setState({
                logoImage:source
            })
        });
    }

    render() {
        const {getFieldProps} = this.props.form;
        return (
            <View style={styles.container}>
                <NavTitle
                    title='修改资料'
                    leftButton = {true}
                    leftImg = {require('../imgs/left.png')}
                    leftText = {'返回'}
                    leftHander = {()=>{this.props.navigator.pop()}}
                    headColor = '#fbdc3a'
                />
                <View style={styles.content}>

                    <View style={styles.logoHead}>
                        <Image source={this.state.logoImage} style={styles.logoImg}/>
                        <TouchableOpacity style={styles.logoBtn} onPress={this._selectLogo.bind(this)}>
                            <Text style={styles.logoTxt}>选择头像</Text>
                        </TouchableOpacity>
                        <Text style={{marginLeft:10}}>100*100</Text>
                    </View>


                    <InputItem
                        clear
                        placeholder="昵称"
                        style={{borderWidth:1/PixelRatio.get(),marginLeft:0,borderColor:'#ddd',borderRadius:2,paddingLeft:5,marginTop:5}}
                        {...getFieldProps('name',{
                            rules: [{required: true}],
                        })}
                        maxLength = {10}
                    />


                    <View style={styles.addressSel}>
                        <TouchableOpacity style={styles.addrlabel} onPress={this._selectProvice.bind(this)}>
                            <Text style={styles.addrIcon}>*</Text>
                            <Text style={styles.addrName}>省份</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.addrlabel} onPress={this._selectCity.bind(this)}>
                            <Text style={styles.addrIcon}>*</Text>
                            <Text style={styles.addrName}>城市</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.addrlabel} onPress={this._selectCounty.bind(this)}>
                            <Text style={styles.addrIcon}>*</Text>
                            <Text style={styles.addrName}>县(区)</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.addrlabel} onPress={this._selectStreet.bind(this)}>
                            <Text style={styles.addrIcon}>*</Text>
                            <Text style={styles.addrName}>镇(街道)</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={{paddingLeft:0,marginTop:10}}>
                        <Text>地址选择:{
                            this.state.resultAddr.join('-')
                        }</Text>
                    </View>


                    <TouchableHighlight
                        style={styles.loginBtn}
                        onPress={this._register.bind(this)}
                    >
                        <Text style={styles.loginText}>确认修改资料</Text>
                    </TouchableHighlight>
                </View>
                <ActivityIndicator
                    toast
                    text="数据加载中..."
                    animating={this.state.animating}
                />
            </View>
        )
    }

}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#FFF',
        flex: 1,
    },
    itemStyle:{
        flexDirection:'row'
    },
    keys:{
        marginRight:10,
    },
    content:{
        padding:20,
        paddingTop:0
    },
    textInput:{
        padding:5,
        paddingLeft:10,
        borderWidth:1/PixelRatio.get(),
        marginTop:20,
        borderRadius:4,
        borderColor:'#CCC',
        backgroundColor:'#FFF'
    },
    logoHead:{
        flexDirection:'row',
        alignItems:'center',
        marginTop:5,
        marginBottom:5
    },
    logoImg:{
        width:80,
        height:80,
        marginRight:5
    },
    logoBtn:{
        borderWidth:1/PixelRatio.get(),
        borderRadius:3,
        borderColor:'#CCC',
        backgroundColor:'#FFF',
        padding:4,
        paddingLeft:5,
        paddingRight:5
    },
    selectInput:{
        backgroundColor:'#FFF',
        marginTop:20,
    },
    loginBtn:{
        padding:15,
        backgroundColor:'#FBDC3A',
        marginTop:20,
        borderRadius:3,
        justifyContent:'center',
        alignItems:'center'
    },
    telInput:{
        flex:1,
        borderWidth:1/PixelRatio.get(),
        borderRadius:4,
        borderColor:'#DDD',
        borderRightWidth:0,
        paddingLeft:5
    },
    btnInput:{
        flexDirection:'row',
        backgroundColor:'#FFF',
        marginTop:10,
    },
    sendBtn:{
        backgroundColor:'#FBDC3A',
        paddingLeft:5,
        paddingRight:5,
        marginLeft:-3,
        justifyContent:'center',
        alignItems:'center',
        borderColor:'#DDD',
        borderBottomWidth:1/PixelRatio.get(),
        borderTopWidth:1/PixelRatio.get(),
        borderRightWidth:1/PixelRatio.get(),
    },
    loginText:{
        fontSize:16
    },
    footTip:{
        flexDirection:'row',
        justifyContent:'flex-end',
        marginTop:10
    },
    tip1:{
        color:'#c9caca'
    },
    tip2:{
        color:'#e83828',
        textDecorationLine:'underline'
    },
    addressSel:{
        flexDirection:'row',
        paddingLeft:0,
        marginTop:10
    },
    addrlabel:{
        flexDirection:'row',
        flex:1
    },
    addrIcon:{
        color: '#F00',
        fontSize:16,
        marginRight:5
    },
    addrName:{
        fontSize:16
    }
});

export default createForm()(EditPerson);